﻿using Microsoft.Office.InfoPath;
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace InfoPathHelpers
{
    public class DataSourceContext : IDataSourceContext
    {
        protected DataSource _DataSource;
        protected FixedPositionNavigator _Root;
        private string _Name;
        private bool _IsReadOnly;

        public DataSourceContext(DataSource dataSource)
        {
            _DataSource = dataSource;
            _Root = new FixedPositionNavigator(dataSource.CreateNavigator());
            _Name = dataSource.Name;
            _IsReadOnly = dataSource.ReadOnly;
            if(NamespaceManager == null)
            {
                NamespaceManager = TemplateExplorer.NamespaceResolution.GetNamespaceManager(Navigator);
            }
        }

        public DataSourceContext(DataSource dataSource, IXmlNamespaceResolver namespaceManager) : this(dataSource)
        {
            NamespaceManager = namespaceManager;
        }

        public DataSourceContext(XmlFormHostItem form, string dataSourceName) 
            : this(form.DataSources[dataSourceName]) 
        { 
            
        }

        public string Name
        {
            get { return _Name; }
        }

        public bool IsReadOnly
        {
            get { return _IsReadOnly; }
        }

        public FixedPositionNavigator Root
        {
            get { return _Root; }
        }

        public System.Xml.XPath.XPathNavigator Navigator
        {
            get { return _Root.Clone(); }
        }

        public IXmlNamespaceResolver NamespaceManager { get; set; }

        public System.Xml.XPath.XPathNavigator SelectSingleNode(string xPath)
        {
            return _Root.SelectSingleNode(xPath, NamespaceManager);
        }

        public System.Xml.XPath.XPathNodeIterator Select(string xPath)
        {
            return _Root.Select(xPath, NamespaceManager);
        }

        public void ReQuery()
        {
            _DataSource.QueryConnection.Execute();
        }


        public object Evaluate(string xPath)
        {
            return _Root.Evaluate(xPath, NamespaceManager);
        }
    }
}
